﻿using Microsoft.Extensions.Options;
using System.Net;

namespace SamsoniteProject.MiddleWare
{
    public class Ipfilter
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<Ipfilter> _logger;
        private readonly IConfiguration _configuration;

        public Ipfilter(RequestDelegate next, ILogger<Ipfilter> logger, IConfiguration configuration)
        {
            _next = next;
            _logger = logger;
            _configuration = configuration;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var allowedIPs = _configuration.GetSection("IPWhitelist:AllowedIPs").Get<string[]>();

            var remoteIpAddress = context.Connection.RemoteIpAddress;

            if (!IsIPAllowed(remoteIpAddress, allowedIPs))
            {
                _logger.LogWarning($"IP address {remoteIpAddress} is not allowed.");

                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }

            await _next(context);
        }

        private static bool IsIPAllowed(IPAddress ipAddress, string[] allowedIPs)
        {
            foreach (var allowedIP in allowedIPs)
            {
                if (IPAddress.TryParse(allowedIP, out var parsedIP))
                {
                    if (parsedIP.Equals(ipAddress))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
    }
 }
